package server

import (
	"sync/atomic"
	"time"

	"gitee.com/fanshuaiself/wss-gateway/pkg/redis"
	"gitee.com/fanshuaiself/wss-gateway/util"
	"github.com/gorilla/websocket"
)

type connection struct {
	clientId string 
	conn *websocket.Conn

	conHub *connectionHub
	msgHub *messageHub
	state int32
	lastHeartBeat int64 
}

func NewConn(clientId string, conHub *connectionHub, msgHub *messageHub, conn *websocket.Conn) *connection {
	return &connection{
		clientId: clientId,
		conn: conn,
		conHub: conHub,
		msgHub: msgHub,
		state: 0,
		lastHeartBeat: time.Now().Unix(),
	}
}

func (c *connection) Start() {
	if !atomic.CompareAndSwapInt32(&c.state, 0, 1) {
		return 
	}

	c.conHub.Add(c)
	redis.Set(c.clientId, util.GetIp(), time.Hour * 1000)

	go c.receiveMessage()
}

func (c *connection) receiveMessage() {
	for c.state == 1 {
		_, data, err := c.conn.ReadMessage()
		if err != nil {
			c.Close()
			break
		}

		message := &Message{
			Msg: string(data),
		}
		c.msgHub.InMessage(message)
	}
}

func (c *connection) Close() {
	c.conHub.Del(c)
	redis.Del(c.clientId)
	c.conn.Close()

	c.state = 0
}

func (c *connection) WriteMsg(s string) {
	if c.state == 1 {
		c.conn.WriteMessage(websocket.TextMessage, []byte(s))
	}
}

